<template>
  <div class="planting-management-container agri-page-container">
    <div class="agri-page-header">
      <div class="agri-page-title">
        <el-icon><Crop /></el-icon>
        <span>种植管理</span>
      </div>
      <div class="agri-page-actions">
        <el-button type="primary" @click="handleAddPlanting">
          <el-icon><Plus /></el-icon>
          添加种植记录
        </el-button>
      </div>
    </div>
    
    <!-- 过滤栏 -->
    <el-card class="filter-card agri-card">
      <div class="filter-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索种植记录"
          prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
        
        <el-select v-model="statusFilter" placeholder="种植状态" clearable @change="handleFilter">
          <el-option label="全部" value="" />
          <el-option label="生长中" value="growing" />
          <el-option label="已收获" value="harvested" />
        </el-select>
        
        <el-select v-model="landFilter" placeholder="所属地块" clearable @change="handleFilter">
          <el-option label="全部" value="" />
          <el-option 
            v-for="land in lands" 
            :key="land.id" 
            :label="land.name" 
            :value="land.id" 
          />
        </el-select>
      </div>
    </el-card>
    
    <!-- 种植列表 -->
    <el-card class="list-card agri-card" v-loading="loading">
      <div class="agri-table-wrapper">
        <el-table
          :data="filteredPlantings"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="cropName" label="农作物名称" min-width="120" />
          <el-table-column prop="landName" label="所属地块" min-width="120" />
          <el-table-column prop="plantingDate" label="种植日期" min-width="120">
            <template #default="scope">
              {{ formatDate(scope.row.plantingDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="harvestDate" label="预计收获日期" min-width="120">
            <template #default="scope">
              {{ formatDate(scope.row.harvestDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="plantingArea" label="种植面积" min-width="100">
            <template #default="scope">{{ scope.row.plantingArea }} 亩</template>
          </el-table-column>
          <el-table-column prop="expectedYield" label="预计产量" min-width="100">
            <template #default="scope">{{ scope.row.expectedYield }} kg</template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
                {{ scope.row.statusName || (scope.row.status === 0 ? '生长中' : '已收获') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <div class="agri-operations">
                <el-button type="success" size="small" @click="handleEditPlanting(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDeletePlanting(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper, total"
          :total="totalPlantings"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 对话框 -->
    <div class="agri-dialog-wrapper">
      <el-dialog
        v-model="plantingDialogVisible"
        :title="isEdit ? '编辑种植记录' : '添加种植记录'"
        width="650px"
      >
        <el-form :model="plantingForm" :rules="rules" ref="plantingFormRef" label-width="100px">
          <el-form-item label="农作物名称" prop="name">
            <el-input v-model="plantingForm.name" placeholder="请输入农作物名称" />
          </el-form-item>
          
          <el-form-item label="所属地块" prop="landId">
            <el-select v-model="plantingForm.landId" placeholder="请选择地块">
              <el-option 
                v-for="land in lands" 
                :key="land.id" 
                :label="land.name" 
                :value="land.id" 
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="农作物品种" prop="cropVariety">
            <el-input v-model="plantingForm.cropVariety" placeholder="请输入农作物品种，如：软香粳" />
          </el-form-item>
          
          <el-form-item label="种植日期" prop="plantingDate">
            <el-date-picker 
              v-model="plantingForm.plantingDate" 
              type="datetime" 
              placeholder="选择种植日期"
              value-format="YYYY-MM-DDTHH:mm:ss"
            />
          </el-form-item>
          
          <el-form-item label="预计收获日期" prop="harvestDate">
            <el-date-picker 
              v-model="plantingForm.harvestDate" 
              type="datetime" 
              placeholder="选择预计收获日期"
              value-format="YYYY-MM-DDTHH:mm:ss"
            />
          </el-form-item>
          
          <el-form-item label="种植面积(亩)" prop="area">
            <el-input-number v-model="plantingForm.area" :precision="1" :min="0.1" />
          </el-form-item>
          
          <el-form-item label="预计产量(kg)" prop="estimatedYield">
            <el-input-number v-model="plantingForm.estimatedYield" :precision="0" :min="1" />
          </el-form-item>
          
          <el-form-item label="种植状态" prop="status">
            <el-select v-model="plantingForm.status" placeholder="请选择状态" @change="handleStatusChange">
              <el-option label="生长中" value="growing" />
              <el-option label="已收获" value="harvested" />
            </el-select>
          </el-form-item>
          
          <el-form-item 
            label="实际产量(kg)" 
            prop="actualYield" 
            v-if="plantingForm.status === 'harvested'"
            :rules="[{ required: true, message: '已收获状态下必须填写实际产量', trigger: 'blur' }]"
          >
            <el-input-number v-model="plantingForm.actualYield" :precision="0" :min="1" />
          </el-form-item>
          
          <el-form-item label="备注" prop="notes">
            <el-input 
              v-model="plantingForm.notes" 
              type="textarea" 
              placeholder="请输入备注信息" 
              :rows="3"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="plantingDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    
    <!-- 详情对话框 -->
    <div class="agri-dialog-wrapper">
      <el-dialog
        v-model="detailDialogVisible"
        title="种植详情"
        width="700px"
      >
        <!-- 详情内容 -->
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useFarmerStore } from '../../store';
import { Plus, Search, Crop } from '@element-plus/icons-vue';

// 状态管理
const farmerStore = useFarmerStore();

// 加载状态
const loading = ref(false);

// 搜索和筛选
const searchQuery = ref('');
const statusFilter = ref('');
const landFilter = ref('');

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const totalPlantings = ref(0);

// 地块数据
const lands = ref([]);

// 种植记录数据
const plantings = ref([]);

// 对话框
const plantingDialogVisible = ref(false);
const isEdit = ref(false);
const plantingFormRef = ref(null);
const detailDialogVisible = ref(false);

// 表单数据
const plantingForm = reactive({
  id: '',
  name: '',
  landId: '',
  cropVariety: '',
  plantingDate: '',
  harvestDate: '',
  area: 1,
  estimatedYield: 100,
  status: 'growing',
  actualYield: 0,
  notes: ''
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入农作物名称', trigger: 'blur' }],
  landId: [{ required: true, message: '请选择地块', trigger: 'change' }],
  cropVariety: [{ required: true, message: '请输入农作物品种', trigger: 'blur' }],
  plantingDate: [{ required: true, message: '请选择种植日期', trigger: 'change' }],
  harvestDate: [{ required: true, message: '请选择预计收获日期', trigger: 'change' }],
  area: [{ required: true, message: '请输入种植面积', trigger: 'blur' }],
  estimatedYield: [{ required: true, message: '请输入预计产量', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 计算过滤后的种植记录
const filteredPlantings = computed(() => {
  return plantings.value.filter(planting => {
    // 搜索条件
    const matchesSearch = 
      (planting.cropName || '').toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      (planting.remark || '').toLowerCase().includes(searchQuery.value.toLowerCase());
    
    // 状态筛选
    const matchesStatus = statusFilter.value ? 
      (statusFilter.value === 'growing' && planting.status === 0) || 
      (statusFilter.value === 'harvested' && planting.status === 1) : true;
    
    // 地块筛选
    const matchesLand = landFilter.value ? planting.landId === landFilter.value : true;
    
    return matchesSearch && matchesStatus && matchesLand;
  });
});

// 加载地块数据
async function loadRelatedData() {
  try {
    // 加载土地数据
    lands.value = await farmerStore.fetchLands();
  } catch (error) {
    console.error('获取土地数据失败', error);
    ElMessage.error('获取土地数据失败');
  }
}

// 加载种植记录
async function loadPlantings() {
  loading.value = true;
  try {
    // 从API获取真实数据
    const result = await farmerStore.fetchPlantings();
    console.log('获取到的种植记录原始数据:', result);
    
    // 确保 result 是数组
    if (Array.isArray(result)) {
      plantings.value = result;
      totalPlantings.value = result.length;
    } else if (result && result.records && Array.isArray(result.records)) {
      // 处理分页数据
      plantings.value = result.records;
      totalPlantings.value = result.total || result.records.length;
    } else {
      plantings.value = [];
      totalPlantings.value = 0;
    }
    
    console.log('处理后的种植记录:', plantings.value);
    console.log('总记录数:', totalPlantings.value);
  } catch (error) {
    console.error('获取种植记录失败', error);
    ElMessage.error('获取种植记录失败: ' + (error.message || '未知错误'));
    plantings.value = [];
    totalPlantings.value = 0;
  } finally {
    loading.value = false;
  }
}

// 搜索处理
function handleSearch() {
  currentPage.value = 1;
}

// 筛选处理
function handleFilter() {
  currentPage.value = 1;
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
  loadPlantings();
};

// 处理每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadPlantings();
};

// 添加种植记录
function handleAddPlanting() {
  isEdit.value = false;
  resetForm();
  plantingDialogVisible.value = true;
}

// 编辑种植记录
function handleEditPlanting(row) {
  isEdit.value = true;
  resetForm();
  
  // 复制数据到表单，处理字段映射
  plantingForm.id = row.id;
  plantingForm.name = row.cropName;
  plantingForm.landId = row.landId;
  plantingForm.cropVariety = row.cropVariety;
  plantingForm.plantingDate = row.plantingDate;
  plantingForm.harvestDate = row.harvestDate;
  plantingForm.area = row.plantingArea;
  plantingForm.estimatedYield = row.expectedYield;
  plantingForm.status = row.status === 0 ? 'growing' : 'harvested';
  plantingForm.actualYield = row.actualYield || 0;
  plantingForm.notes = row.remark;
  
  plantingDialogVisible.value = true;
}

// 查看种植记录
function handleViewPlanting(row) {
  // 跳转到详情页或显示详情对话框
  console.log('查看记录', row);
}

// 删除种植记录
function handleDeletePlanting(row) {
  ElMessageBox.confirm('确定要删除这条种植记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际调用API删除
      await farmerStore.removePlanting(row.id);
      ElMessage.success('删除成功');
      loadPlantings();
    } catch (error) {
      console.error('删除失败', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
}

// 重置表单
function resetForm() {
  if (plantingFormRef.value) {
    plantingFormRef.value.resetFields();
  }
  
  plantingForm.id = '';
  plantingForm.name = '';
  plantingForm.landId = '';
  plantingForm.cropVariety = '';
  plantingForm.plantingDate = '';
  plantingForm.harvestDate = '';
  plantingForm.area = 1;
  plantingForm.estimatedYield = 100;
  plantingForm.status = 'growing';
  plantingForm.actualYield = 0;
  plantingForm.notes = '';
}

// 提交表单
async function submitForm() {
  if (!plantingFormRef.value) return;
  
  await plantingFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 检查记录是否已收获
        const isHarvested = plantingForm.status === 'harvested';
        
        // 如果是已收获状态，但没有填写实际产量，则使用预计产量
        if (isHarvested && (!plantingForm.actualYield || plantingForm.actualYield <= 0)) {
          plantingForm.actualYield = plantingForm.estimatedYield || 1;
        }
        
        // 准备提交的数据，处理字段映射
        const submitData = {
          id: plantingForm.id || undefined, // 如果是新增，不传id
          landId: plantingForm.landId,
          cropName: plantingForm.name,
          cropVariety: plantingForm.cropVariety,
          plantingArea: plantingForm.area,
          plantingDate: plantingForm.plantingDate,
          harvestDate: plantingForm.harvestDate,
          expectedYield: plantingForm.estimatedYield,
          status: plantingForm.status === 'growing' ? 0 : 1,
          actualYield: isHarvested ? plantingForm.actualYield : null,
          remark: plantingForm.notes || ''
        };
        
        console.log('提交的数据:', submitData);
        
        if (isEdit.value) {
          // 编辑操作
          const result = await farmerStore.updatePlanting(plantingForm.id, submitData);
          console.log('更新结果:', result);
          ElMessage.success('更新成功');
        } else {
          // 添加操作
          const result = await farmerStore.addNewPlanting(submitData);
          console.log('添加结果:', result);
          ElMessage.success('添加成功');
        }
        
        plantingDialogVisible.value = false;
        await loadPlantings(); // 确保使用await等待数据加载完成
      } catch (error) {
        console.error('操作失败', error);
        ElMessage.error('操作失败: ' + (error.message || '未知错误'));
      }
    }
  });
}

// 日期格式化函数
function formatDate(dateString) {
  if (!dateString) return '';
  
  // 尝试解析日期
  let date;
  if (typeof dateString === 'string') {
    // 如果是ISO格式的日期字符串
    if (dateString.includes('T')) {
      date = new Date(dateString);
    } 
    // 如果是简单的日期字符串，如 "2025-03-08"
    else {
      const parts = dateString.split('-');
      if (parts.length === 3) {
        date = new Date(parts[0], parts[1] - 1, parts[2]);
      } else {
        return dateString; // 无法解析，返回原始字符串
      }
    }
  } else {
    date = new Date(dateString);
  }
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) return dateString;
  
  // 格式化日期
  const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
  return date.toLocaleDateString('zh-CN', options);
}

// 处理状态变化
function handleStatusChange(value) {
  if (value === 'harvested' && !plantingForm.actualYield) {
    plantingForm.actualYield = plantingForm.estimatedYield || 1; // 默认使用预计产量
  }
}

// 初始化
onMounted(async () => {
  await loadRelatedData();
  await loadPlantings();
});
</script>

<style scoped>
.planting-management-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: var(--el-text-color-primary);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  gap: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.agri-page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.agri-page-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.agri-page-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.agri-table-wrapper {
  margin-bottom: 20px;
}

.agri-operations {
  display: flex;
  gap: 10px;
}

.agri-dialog-wrapper {
  margin-top: 20px;
}
</style> 